<?php

$CI = & get_instance();

/**
 * 
 * @global type $CI
 * @param type $table
 * @param type $where
 * @param type $select
 * @return type
 */
function get_user($table, $where = array(), $select = array('*')) {
    global $CI;
    $CI->db->select($select);
    $sql = $CI->db->get_where($table, $where);
    if ($sql->num_rows() > 1) {
        return $sql->result();
    } elseif ($sql->num_rows() == 1) {
        return $sql->row();
    } else {
        return array();
    }
}

function form_val($form = false) {
    global $CI;
    if ($form) {
        if ($post = $CI->session->userdata('post')) {
            $form = explode('=>', $form);
            if (isset($post[$form[0]])) {
                if (isset($form[1]))
                    return $post[$form[0]][$form[1]];
                else
                    return $post[$form[0]];
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function get_sub_cats($id = false, $trash = false) {
    global $CI;
    $return = array();
    if ($id) {
        $CI->load->model('admin/categories_model', 'cats');
        if ($trash)
            $return = $CI->cats->get(array('parent' => $id), false, 'result', FALSE, false, TRUE);
        else
            $return = $CI->cats->get(array('parent' => $id));
    }
    return $return;
}

function get_languages() {
    global $CI;
    $CI->db->select(array('code', 'active', 'default'));
    return $CI->db->get_where('languages', array('active' => '1'))->result();
}

/**
 * 
 * @global type $CI
 * @param type $user_id
 * @return type
 */
function get_addressbook($user_id, $default = false) {
    global $CI;
    if ($default == true) {
        $CI->db->where('default', 'YES');
    }
    $sql = $CI->db->get_where('addressbook', array('user_id' => $user_id));
    return $sql->result();
}

function get_validation_errors() {
    global $CI;
    $message['url'] = current_url();
    $message['type'] = 'validation_error';
    $message['message'] = validation_errors();
    $CI->themes->set_message($message);
}

function get_input_types() {
    return array('text', 'textarea', 'file', 'ajaxupload', 'number', 'email', 'date', 'checkbox');
}

function get_save_error() {
    global $CI;
    $message['url'] = current_url();
    $message['type'] = 'error';
    $message['message'] = 'message_save_error';
    $CI->themes->set_message($message);
}

function get_roles($roles = array()) {
    global $CI;
    $data['permsion'] = unserialize($roles);
    $CI->load->view('admin/helper/action/create_manager', $data);
}

/**
 * 
 * @global type $CI
 * @return type
 */
function get_bank_list($select = '') {
    global $CI;
    $result = array();
    $sql = $CI->db->get_where('bank', array('publish' => 'YES'));
    if (!empty($select)) {
        $result[''] = $select;
    }
    foreach ($sql->result() as $val) {
        $result[$val->id] = $val->title;
    }
    return $result;
}

/**
 * 
 * @global type $CI
 * @param type $id
 * @param type $coulm
 * @return type
 */
function get_bank($id, $coulm = 'title') {
    global $CI;

    $sql = $CI->db->get_where('bank', array('id' => $id));
    $row = $sql->row();

    return $row->$coulm;
}

function get_store_details($details = false) {
    $return = array();
    foreach ($details as $dt) {
        $val = @unserialize($dt->value);
        if ($val === false) {
            $return[$dt->name] = $dt->value;
        } else {
            $key = explode('_', $dt->name);
            $return['staticpages_title'][$key[1]] = $val['title'];
            $return['staticpages_content'][$key[1]] = $val['content'];
        }
    }
    return $return;
}

function get_explode($data = FALSE) {
    if ($data)
        return explode(',', $data);
    else
        return FALSE;
}

/**
 * 
 * @global type $CI
 * @param type $coulm
 * @return type
 */
function get_option($code = false) {
    global $CI;
    $CI->db->select('value');
    $sql = $CI->db->get_where('settings', array('code' => $code));
    $row = $sql->row();
    return $row->value;
}

/**
 * 
 * @global type $CI
 * @param type $id
 * @return type
 */
function get_one_addressbook($id) {
    global $CI;

    $sql = $CI->db->get_where('addressbook', array('id' => $id));
    $row = $sql->row();

    return $row;
}

/**
 * 
 * @global type $CI
 * @param type $number
 * @return type
 */
function get_segment($number = 1) {
    global $CI;
    return strtolower($CI->uri->segment($number));
}

/**
 * 
 * @global type $CI
 * @param type $id
 * @param type $statues_id
 * @param type $user_id
 * @param type $note
 */
function item_create_history($id, $statues_id, $user_id, $note = '', $company = array()) {
    global $CI;

    if (!empty($company['company'])) {
        $add_company = $company['company'];
    } else {
        $add_company = '';
    }

    if (!empty($company['track'])) {
        $track = $company['track'];
    } else {
        $track = '';
    }

    if (is_array($id)) {
        foreach ($id as $value) {
            $CI->db->insert('item_history', array('item_id' => $value, 'statues_id' => $statues_id, 'user_id' => $user_id, 'note' => $note, 'create_date' => date('Y-m-d H:i:s'), 'company' => $add_company, 'track' => $track));
        }
    } else {
        $CI->db->insert('item_history', array('item_id' => $id, 'statues_id' => $statues_id, 'user_id' => $user_id, 'note' => $note, 'create_date' => date('Y-m-d H:i:s')));
    }
}

/**
 * 
 * @global type $CI
 * @param type $id
 * @param type $order
 * @return type
 */
function get_histroy($id, $order = 'up') {
    global $CI;
    if ($order == 'up') {
        $CI->db->order_by('item_history.id desc');
    } elseif ($order == 'dw') {
        $CI->db->order_by('item_history.id asc');
    } else {
        $CI->db->order_by('item_history.id desc');
    }
    $CI->db->select('users.username , statues.title ,item_history.*', false);
    $CI->db->join('statues', 'statues.id = item_history.statues_id');

    $CI->db->join('users', 'users.id = item_history.user_id');


    $sql = $CI->db->get_where('item_history', array('item_id' => $id));

    return $sql->result();
}

/**
 * 
 * @global type $CI
 * @param type $id
 * @return type
 */
function get_items_under_order($id, $where = array(), $not_in = array()) {
    global $CI;
    $CI->db->select('statues.title AS Statue ,items.*', false);
    $CI->db->join('statues', 'items.statue_id = statues.id');
    if (count($where) > 0) {
        $CI->db->where($where);
    }
    if (count($not_in) > 0) {
        $CI->db->where_not_in('items.statue_id', $not_in);
    }
    $sql = $CI->db->get_where('items', array('order_id' => $id));
    return $sql->result();
}

/**
 * 
 * @global type $CI
 * @param type $id
 * @return type
 */
function get_items_under_box($id) {
    global $CI;
    $sql = $CI->db->get_where('order_box_items', array('order_id' => $id));
    return $sql->result();
}

/**
 * 
 * @global type $CI
 * @param type $id
 * @param type $limit
 * @return type
 */
function get_statues($id, $limit = 1) {
    global $CI;
    $sql = $CI->db->get_where('statues', array('id' => $id));
    if ($limit > 1) {
        return $sql->result();
    } else {
        return $sql->row();
    }
}

/**
 * 
 * @global type $CI
 * @param type $first_empty
 * @return type
 */
function get_statues_list($first_empty = true) {
    global $CI;
    $sql = $CI->db->get_where('statues');
    $result = array();
    if ($first_empty == true) {
        $result[] = $CI->lang->line('label_statues');
    }
    foreach ($sql->result() as $value) {
        $result[$value->id] = $value->title;
    }
    return $result;
}

/**
 * 
 * @global type $CI
 * @param type $user_id
 * @return type
 */
function get_user_discount_shiping_rate($user_id) {
    global $CI;
    $sql = $CI->db->get_where('users', array('id' => $user_id));
    $row = $sql->row();

    return array('discount' => $row->discount_persent, 'shiping_rate' => $row->shipment_rate);
}

/* =========== metohd_get_uri ====== */

function uri_get() {
    $get = '';
    foreach ($_GET as $key => $value) {
        $get.= $key . '=' . $value . '&';
    }

    return rtrim($get, '&'); //join('=&',$_GET);   
}

/**
 * 
 * @param type $get
 * @param type $default
 * @return type
 */
function metohd_get_uri($get = '', $default = '') {

    if (count($_GET) > 0) {

        if (array_key_exists($get, $_GET)) {
            if (!empty($_GET[$get])) {
                return mysql_real_escape_string(trim($_GET[$get]));
            } else {
                return $default;
            }
        } else {
            return $default;
        }
    } else {
        return $default;
        ;
    }
}

/**
 * 
 * @return type
 */
function metohd_get_convert_uri() {

    if (count($_GET)) {
        $url = '';
        foreach ($_GET as $key => $value) {
            $url.=$key . '=' . mysql_real_escape_string($value) . '&';
        }
        return rtrim($url, '&');
    }
}

/**
 * 
 * @global type $CI
 * @param type $first_empty
 * @return type
 */
function get_shipping_companies_list($first_empty = true) {
    global $CI;
    $sql = $CI->db->get_where('shipping_companies');
    $result = array();
    if ($first_empty == true) {
        $result[] = $CI->lang->line('label_select');
    }
    foreach ($sql->result() as $value) {
        $result[$value->id] = $value->title;
    }
    return $result;
}

/**
 * 
 * @global type $CI
 * @param type $username
 * @return type
 */
function get_userid_with_username($username, $type = 'like') {
    global $CI;
    $result = array();
    if ($type == 'like') {
        $CI->db->like('username', $username);
    } elseif ($type == 'where') {
        $CI->db->where('username', $username);
    }

    $sql = $CI->db->get_where('user');
    if ($sql->num_rows()) {
        foreach ($sql->result() as $value) {
            $result[] = $value->id;
        }
        return $result;
    }
}

function get_userid_with_email($email, $type = 'like') {
    global $CI;
    $result = array();
    if ($type == 'like') {
        $CI->db->like('email', $email);
    } elseif ($type == 'where') {
        $CI->db->where('email', $email);
    }

    $sql = $CI->db->get_where('users');
    if ($sql->num_rows()) {
        foreach ($sql->result() as $value) {
            $result[] = $value->id;
        }
        return $result;
    }
}

function get_userdata_with_id($id, $dataselect) {
    global $CI;
    $CI->db->select($dataselect);
    $CI->db->where_in('id', $id);
    $sql = $CI->db->get_where('user');
    if ($sql->num_rows()) {

        return $sql->row_array();
    } else {
        return array('id' => '', 'username' => $CI->lang->line('label_unknow'), 'email' => '', 'user_code' => '', 'mode' => '');
    }
}

/**
 * 
 * @global type $CI
 * @param type $id
 * @param type $dataselect
 * @return type
 */
function get_item($id, $dataselect) {
    global $CI;
    $CI->db->select($dataselect);
    $CI->db->where_in('id', $id);
    $sql = $CI->db->get_where('items');
    if ($sql->num_rows()) {

        return $sql->row_array();
    } else {
        return fasle;
    }
}

/**
 * 
 * @global type $CI
 * @param type $id
 * @return type
 */
function get_shiping_company($id, $culm) {
    global $CI;
    $sql = $CI->db->get_where('shipping_companies', array('id' => $id));
    if ($sql->num_rows()) {
        $row = $sql->row_array();
        if (!is_array($culm)) {
            $culm = explode(',', $culm);
        }

        if (is_array($culm)) {
            foreach ($culm as $value) {
                $row[$value];
            }
        } else {
            $row[$culm];
        }
        return $row;
    }
}

/**
 * 
 * @global type $CI
 * @return type
 */
function get_quick_replay() {
    global $CI;
    $result = array();
    $CI->db->select('quick_replay');
    $sql = $CI->db->get_where('settings');
    $row = $sql->row();
    $quick_replay = explode('|', $row->quick_replay);
    $result[] = $CI->lang->line('label_select');
    foreach ($quick_replay as $key => $value) {
        $value = explode('-', $value);
        $result[$value[1]] = $value[0];
    }

    return form_dropdown('quick_replay', $result, set_value('quick_replay'), 'id="quick_replay"');
}

/**
 * 
 * @global type $CI
 * @param type $data
 * @return type
 */
function session_date($data = 'USER_ID') {
    global $CI;
    return $CI->session->userdata($data);
}

/**
 * 
 * @global type $CI
 * @param type $id
 * @return type
 */
function get_itemsbox_under_bill($id) {
    global $CI;

    if (is_array($id)) {
        $CI->db->where_in('invoice_id', $id);
    } else {
        $CI->db->where('invoice_id', $id);
    }
    $sql = $CI->db->get_where('invoice_box_items');
    $id = array();
    foreach ($sql->result() as $value) {
        $id[] = $value->item_id;
    }

    return $id;
}

function get_invoice_histroy($id, $order = 'desc') {
    global $CI;
    $CI->db->select('invoices_histroy.* ,users.id AS userid,users.username', false);
    $CI->db->order_by('invoices_histroy.id ' . $order);
    $CI->db->join('users', 'invoices_histroy.user_id = users.id');
    $sql_history = $CI->db->get_where('invoices_histroy', array('invoices_histroy.invoice_id' => $id));
    return $sql_history->result();
}

function getrandomstring($length) {

    global $template;
    settype($template, "string");

    $template = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    /* this line can include numbers or not */

    settype($length, "integer");
    settype($rndstring, "string");
    settype($a, "integer");
    settype($b, "integer");

    for ($a = 0; $a <= $length; $a++) {
        $b = rand(0, strlen($template) - 1);
        $rndstring .= $template[$b];
    }

    return $rndstring;
}

/**
 * 
 * @global type $CI
 * @param type $code
 * @param type $user_id
 * @param type $select
 * @return type
 */
function get_coupone_info($code, $user_id, $select = 'discount,id') {

    global $CI;
    $CI->db->select($select);
    $sql = $CI->db->get_where('coupons', array('code' => $code));
    if ($sql->num_rows()) {
        $row = $sql->row();
// if to all user insert user id ti table coupone used to know futher user used this coupone
        if ($row->type == 0 && !empty($user_id)) {
            $CI->db->insert('coupons_used', array('user_id' => $user_id, 'coupon_id' => $row->id, 'create_date' => date('Y-m-d H:i:s')));
        } elseif ($row->type == 1) {
            $CI->db->update('coupons', array('used' => 'YES'), array('id' => $row->id));
        }
        return $row;
    }
}

/**
 * 
 * @global type $CI
 * @return type
 */
function admin_alert() {
    global $CI;
    $result = array();
    $all_count = 0;
// get new items add where satues id = 1 بانتظار التاكد من الطلب
    $new_item = $CI->db->get_where('items', array('statue_id' => 1));
    if ($new_item->num_rows()) {
        $result[] = array('count' => $new_item->num_rows(), 'message' => $CI->lang->line('label_admin_alert'), 'url' => 'orders//?statues=1&dblimit=' . $new_item->num_rows());

        $all_count+=$new_item->num_rows();
    }

// get order where update by user where satues id = 3 طلب معدل من قبل العميل
    $edit_item = $CI->db->get_where('items', array('statue_id' => 3));
    if ($edit_item->num_rows()) {
        $result[] = array('count' => $edit_item->num_rows(), 'message' => $CI->lang->line('label_admin_alert_edit_oders'), 'url' => 'orders//?statues=3&dblimit=' . $button_edit_item->num_rows());
        $all_count+=$edit_item->num_rows();
    }
// get invoice where paid = yes and confirm = no
    $paid_invoices = $CI->db->get_where('order_invoices', array('paid' => 'YES', 'confirm' => 'NO'));
    if ($paid_invoices->num_rows()) {
        $result[] = array('count' => $paid_invoices->num_rows(), 'message' => $CI->lang->line('label_admin_alert_incoive_paid'), 'url' => 'invoices//?paid=YES&confirm=NO&dblimit=' . $paid_invoices->num_rows());
        $all_count+=$paid_invoices->num_rows();
    }


// get shipment not arrival to amricann address where date_of_shipment < NOW() and statues id =15 في الطريق للعنوان الامريكي
    $late_invoices = $CI->db->get_where('items', array('date_of_shipment < ' => date('Y-m-d H:i:s'), 'statue_id' => 15));
    if ($late_invoices->num_rows()) {
        $result[] = array('count' => $late_invoices->num_rows(), 'message' => $CI->lang->line('label_admin_alert_order_shiping_late'), 'url' => 'orders//?late=1&dblimit=' . $late_invoices->num_rows());
        $all_count+=$late_invoices->num_rows();
    }

// get shipment not arrival to amricann address where date_of_arrival < NOW() and statues id =8 تم الشراء
    $late_invoices = $CI->db->get_where('items', array('date_of_arrival < ' => date('Y-m-d H:i:s'), 'statue_id' => '8'));
    if ($late_invoices->num_rows()) {
        $result[] = array('count' => $late_invoices->num_rows(), 'message' => $CI->lang->line('label_admin_alert_order_arrival_late'), 'url' => 'orders//?late=2&dblimit=' . $late_invoices->num_rows());
        $all_count+=$late_invoices->num_rows();
    }


// get wallet if withdraw or add;
    $CI->db->or_where('status', 'pending');
    $CI->db->or_where('status', 'wait');
    $late_wallet = $CI->db->get('wallet');
    if ($late_wallet->num_rows()) {
        $result[] = array('count' => $late_wallet->num_rows(), 'message' => $CI->lang->line('label_admin_alert_wallet'), 'url' => 'userswallet//?status=wait,pending&dblimit=' . $late_wallet->num_rows());
        $all_count+=$late_wallet->num_rows();
    }


// get private message where statues = 0
    $inbox = $CI->db->get_where('private_messages', array('statues' => '0'));
    if ($inbox->num_rows()) {
        $result[] = array('count' => $inbox->num_rows(), 'message' => $CI->lang->line('label_admin_alert_new_message'), 'url' => 'private_messages//?statues=1&dblimit=' . $inbox->num_rows());
        $all_count+=$inbox->num_rows();
    }
    $result['all_count'] = $all_count;
    return $result;
}

/**
 * get site option like title close .....
 * @global type $CI
 * @return type
 */
function site_option() {

    global $CI;

    $sql = $CI->db->get_where('settings', array());

    return $sql->row();
}

/**
 * 
 * @global type $CI
 * @param type $id
 * @param type $select
 * @return type
 */
function get_invoices($id, $select = '*') {
    global $CI;
    $CI->db->select($select);
    $sql = $CI->db->get_where('order_invoices', array('id' => $id));
    $row = $sql->row();

    return $row;
}

function draw_qrbarcode($size = 100, $code) {
    return 'http://chart.googleapis.com/chart?chs=' . $size . 'x' . $size . '&cht=qr&chld=H&chld=|2&chf=a,s,000000|bg,s,FFFFFF&chl=' . urlencode($code);
}

/**
 * 
 * @param type $number
 * @return type
 */
function filter_mobile_number($number) {
// $number=  str_replace('966','',$number);
// if $number == 12 lenght
    if (strlen($number) == 12) {
//cheked if statrt 3 lenght by 966
        if (substr($number, 0, 3) != '966') {
            $number = substr_replace($number, '966', 0, 3);
        }
    } elseif (strlen($number) < 12 && strlen($number) == 9) {
        $number = ltrim($number, '0');
        $number = '966' . $number;
    } else {
        $number = substr_replace($number, '966', 0, (strlen($number) - 9));
    }

//else trim right 0 add 966

    return $number;
}

/**
 * 
 * @param type $value
 * @return string
 */
function value_checkbox($value) {
    if (!empty($value)) {
        return 'YES';
    } else {
        return 'NO';
    }
}

/**
 * display tree link
 * @global type $CI
 * @return string
 */
function admin_Crumb() {
    global $CI;
    $url = uri_string();
    $result = '';
    $url_explode = explode('/', $url);
    if (is_array($url_explode)) {

        if ($url_explode[0] == ADMIN_FOLDER) {
            // delete up index 3
            if (count($url_explode) > 3) {
                for ($i = 3; $i <= count($url_explode); $i++) {
                    unset($url_explode[$i]);
                }
            }

            $result.='<ul class="breadcrumb">';
            $r = 0;
            foreach ($url_explode as $value) {
                $r++;
                if ($value == ADMIN_FOLDER) {
                    $result.= '<li><a href="' . base_url() . ADMIN_FOLDER . '/"><i class="icofont-home"></i>  ' . $CI->lang->line('label_menu_link_' . $value) . '</a><span class="divider">&rsaquo;</span></li>';
                } else {

                    if ($r != count($url_explode)) {
                        $result.= '<li><a href="' . base_url() . ADMIN_FOLDER . '/' . $value . '/">  ' . $CI->lang->line('label_menu_link_' . $value) . '</a><span class="divider">&rsaquo;</span></li>';
                    } else {

                        $result.= '<li class="active">' . $CI->lang->line('label_menu_link_' . $value) . '</li>';
                    }
                }
            }
            $result.='</ul>';
        } else {
            
        }
    } else {
        
    }
    return $result;
}

/**
 * 
 * @param type $path
 * @param type $img
 * @param type $default
 */
function display_img($path, $img, $default = '') {
    $files = str_replace(array('helpers', APPPATH), '', dirname(__FILE__)) . $path . $img;
    $file = base_url() . $path . $img;
    if (!file_exists($files) && !empty($img)) {
        echo $file;
    } else {
        echo base_url() . $path . $default;
    }
}

/**
 * get slider data
 * @global type $CI
 * @return type
 */
function get_slider() {
    global $CI;
    $uri = uri_string();
    if ($uri == '') {
        $sql = $CI->db->get_where('slide', array());
        return $sql->result();
    }
}

function get_shiping_com($where = array(), $limit = 1) {
    global $CI;
    $sql = $CI->db->get_where('shipping_companies', $where);
    if ($limit == 1) {
        return $sql->row();
    } else {
        return $sql->result();
    }
}

//======================= wallet =================//
/**
 * 
 * @global type $CI
 * @param type $user_id
 * @return type
 */
function account_active_wallet($user_id = '') {
    global $CI;
    if (empty($user_id)) {
        $user_id = $CI->user_id;
    }
    $CI->load->model('wallet_model', 'wallet');
    $data = $CI->wallet->get(array('user_id' => $user_id, 'status' => 'active'));
    $credit = 0;
    if ($data) {
        foreach ($data as $da) {
            if ($da->operation == 'plus') {
                $credit += $da->amount;
            } elseif ($da->operation == 'minus') {
                $credit -= $da->amount;
            }
        }
        return $credit;
    }
}

function account_all_wallet($user_id = '') {
    global $CI;
    if (empty($user_id)) {
        $user_id = $CI->user_id;
    }
    $CI->load->model('wallet_model', 'wallet');
    $data = $CI->wallet->get(array('user_id' => $user_id, 'status !=' => 'rejected'));
    $credit = 0;
    if ($data) {
        foreach ($data as $da) {
            if ($da->operation == 'plus') {
                $credit += $da->amount;
            } elseif ($da->operation == 'minus') {
                $credit -= $da->amount;
            }
        }
        return $credit;
    }
}

function account_wallet($user_id = '') {
    global $CI;
    if (empty($user_id)) {
        $user_id = $CI->user_id;
    }
    return $CI->wallet->account($user_id);
}

/**
 * 
 * @global type $CI
 * @param type $id
 * @return type
 */
function get_wallet_bank($id) {
    global $CI;
    $CI->db->limit(1);
    $sql = $CI->db->get_where('wallet_bank', array('wallet_id' => $id, 'type' => 'wallet'));

    return $sql->row();
}

function get_inv_bank($id) {
    global $CI;
    $CI->db->limit(1);
    $sql = $CI->db->get_where('wallet_bank', array('wallet_id' => $id, 'type' => 'inv'));

    return $sql->row();
}

function get_date($date) {
    $date = date('Y-m-d H:i:s', strtotime($date));

    return $date;
}

/**
 * 
 * @return int
 */
function get_discount_bank() {
    return 15;
}

/**
 * 
 * @global type $CI
 * @return type
 */
function basket_count() {
    /* global $CI;
      if (!empty($CI->user_id)) {
      $sql = $CI->db->get_where('items', array('user_id' => $CI->user_id, 'temporary' => 'YES', 'type' => 'item_paid'));
      return $sql->num_rows();
      } else {
      return 0;
      } */
}

function get_current_url() {
    global $CI;
    return explode('/', current_url());
}

function is_found_balance($balance, $user_id) {
    global $CI;
    $sql = $CI->db->get_where('users_balance', array('user_id' => $user_id, 'title' => $balance));
    return $sql->num_rows();
}



function pr($array=array()){
    
    if(is_array($array)){
        echo '<pre dir="ltr">';
        print_r($array); 
         echo '</pre>';
    }else{
        echo $array;
    }
   
  
}
?>
